/*
 * 
 * manages two items
 * one enabled and one disabled at any given time
 * clicking the panel will cause a toggle operation
 */

function Toggle(_did, _callback, config) {
	if(!_did){
		alert('Cannot make Toggle without div id');
		return null;
	}else{
		var el=document.getElementById(_did);
		if(el===null) {
			alert(_did+' does not exist');
			return null;
		}
	}
	var currentValue=null;
	var className=config.className;
	var me=this;
	var callback=_callback;
	var did=_did;
	var ttid=did+'-id';
	var elements=[];
	this.enabled=true;
	this.isEnabled=function(){return me.enabled;};
	this.setEnabled=function(enabled) {
		me.enabled=enabled;
	}
	this.getVal=function() {
		for(var i in elements){
			var el=elements[i];
			if(i==currentValue){
				return el.val;
			}
		}
		return 'BOGUS';
	}
	this.toggle=function() {
		if(!me.enabled)return;
		currentValue=(currentValue===0)?1:0;
		var sel=null;
		for(var i in elements){
			var el=elements[i];
			if(i==currentValue){
				el.className=className+'-'+i;
				sel=el;
			}else{
				el.className=className+'-disabled-'+i;
			}
		}
		return sel.val;
	};
	/*
	 * only forwards if the element is enabled
	 */
	this.callbackDelegate=function(e) {
		if(!me.enabled){return;}
		var sel = me.toggle();
		callback(sel);
	};
	this.mkli=function(cls,val){
		var li=document.createElement('li');
		li.className=cls;
		li.val=val;
		return li;
	};
	this.init=function() {
		var el=document.getElementById(did);
		var ul=document.createElement('ul');
		ul.id = ttid;
		ul.onclick=me.callbackDelegate;
		ul.className=className;
		if(config.def === 'undefined' || config.def === 0) {
			elements[elements.length]=me.mkli(className+'-0',config.val0);
			elements[elements.length]=me.mkli(className+'-disabled-1',config.val1);
			currentValue=0;
		} else {
			elements[elements.length]=me.mkli(className+'-disabled-0',config.val0);
			elements[elements.length]=me.mkli(className+'-1',config.val1);
			currentValue=1;
		}
		for (var i in elements) {
			ul.appendChild(elements[i]);
		}
		el.appendChild(ul);
	}
	me.init();
	me.setEnabled(me.enabled);
}
